package com.liu.producer.resolver;


import com.liu.agreement.Agreement;
import com.liu.message.MessageTypeEnum;
import com.liu.producer.resolver.impl.ResponseMessageResolver;
import com.liu.resolver.Resolver;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @param
 * @BelongsProject: MessageQueueDEMO
 * @BelongsPackage: com.liu.producer.resolver
 * @author: L
 * @Date: 2023/10/15 14:55
 * @return
 */

public class MessageResolverProvider {
    private static volatile MessageResolverProvider messageResolverProvider;
    private static final List<Resolver> resolvers=new CopyOnWriteArrayList<>();

    private MessageResolverProvider() {
        registerResolver(new ResponseMessageResolver());
    }

    public static Object resovler(Agreement agreement) {
        MessageResolverProvider instance = getInstance();
        Resolver resovler = instance.getResovler(agreement.getMessageType());
        return resovler.resolve(agreement);
    }

    public static boolean registerResolver(Resolver resolver){
        return resolvers.add(resolver);
    }

    public Resolver getResovler(MessageTypeEnum messageType){
        for (Resolver resolver:resolvers){
            if (resolver.support(messageType)){
                return resolver;
            }
        }
        throw new RuntimeException("找不到对应类型的解析器,消息类型: " + messageType);
    }


    private static MessageResolverProvider getInstance() {
        if (messageResolverProvider==null){
            synchronized (MessageResolverProvider.class){
                if (messageResolverProvider==null){
                    messageResolverProvider=new MessageResolverProvider();
                }
            }
        }
        return messageResolverProvider;
    }
}
